import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:sph_driver/AppConfig/LocalStorage.dart';
import 'package:sph_driver/Main/MyWallet/PayAuthentication.dart';


import '../../AppConfig/Config.dart';
import '../../AppConfig/ShowDialog.dart';
import '../../Tabbar/TabbarView.dart';
import '../../http/api.dart';
import 'FreightPaymentSuccessful.dart';

class PayTheFreight extends StatefulWidget {
  const PayTheFreight({super.key, required this.dataMap, required this.payType, required this.freight, required this.freightType, });
  final Map dataMap;
  final String freight;
  final int freightType;
  //1抢单 2确认协议
  final int payType;
  @override
  State<PayTheFreight> createState() => _PayTheFreightState();
}

class _PayTheFreightState extends State<PayTheFreight> {
  int payType=-1;
  String insureStr="";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print(widget.dataMap);
    getInsureMoney();
  }
  Future<void>  getInsureMoney() async {
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header + 'api/goods/goods/pay/userPayAmount',
      data: {
        "goodsId":widget.dataMap['goodsId']!=null? widget.dataMap['goodsId']:widget.dataMap['id'],
        "loadPlaceInfo":widget.dataMap['loadPlaceInfo'],
        "unloadPlaceInfo":widget.dataMap['unloadPlaceInfo'],
        "insurance":widget.dataMap['goodsInsurance'],
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          insureStr=jsonMap['data'];
        } else {

          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
        appBar: AppBar(
        title:Text( "支付",style: TextStyle(fontWeight: FontWeight.w300),),
      backgroundColor: Colors.white,
      centerTitle: true,
        ),
      body:Column(
        children: [
          Expanded(child: ListView(
            children: [

              Container(
                margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                padding: EdgeInsets.only(top: 22.h,bottom: 23.h),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  children: [
                     Row(
                       mainAxisAlignment: MainAxisAlignment.center,
                       crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                              Text("费用 ¥",style: TextStyle(color: Color.fromRGBO(228, 28, 35, 1),fontWeight: FontWeight.w600,fontSize: 14.sp),),
                          //     if( widget.payType==2)
                          //      Text((widget.freight).toString(),style: TextStyle(color: Color.fromRGBO(228, 28, 35, 1),fontSize: 20.sp,fontWeight: FontWeight.w600),),
                          // if( widget.payType==1)
                          Text((insureStr).toString(),style: TextStyle(color: Color.fromRGBO(228, 28, 35, 1),fontSize: 20.sp,fontWeight: FontWeight.w600),),

                        ],
                    ),

                    Container(
                      padding: EdgeInsets.all(10.h),
                      margin: EdgeInsets.only(top: 14.h),
                      width: screenSize.width-20.w,
                      height: 40.h,
                      color: Color.fromRGBO(251, 241, 233, 1),
                      child: Text("请选择支付方式",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                    ),
                    SizedBox(height: 10.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/余额支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text("余额支付",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                Text("可用"+"200.15"+"元",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                              ],
                            ),

                          ],
                        ),
                        IconButton(onPressed: (){
                          setState(() {
                            payType=1;
                          });
                        }, icon:payType==1?Icon(Icons.check_circle,color: MyColors.themeColor,):Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/微信支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Text("微信支付",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                          ],
                        ),
                        IconButton(onPressed: (){
                          setState(() {
                            payType=2;
                          });
                        }, icon:payType==2?Icon(Icons.check_circle,color: MyColors.themeColor,):Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/支付宝支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Text("支付宝支付",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                          ],
                        ),
                        IconButton(onPressed: (){
                          setState(() {
                            payType=3;
                          });
                        }, icon:payType==3?Icon(Icons.check_circle,color: MyColors.themeColor,):Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/银行卡支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Text("招商银行储蓄卡(9999)",style: TextStyle(color: Colors.black,),),
                          ],
                        ),
                        Row(
                          children: [
                            BrnTagCustom.buildBorderTag(
                              tagText: '支付立减6.9元',
                              textColor:Color.fromRGBO(246, 57, 13, 1),
                              borderColor: Color.fromRGBO(246, 57, 13, 1),
                              borderWidth: 1,
                              fontSize: 12.sp,
                            ),
                            IconButton(onPressed: (){
                              setState(() {
                                payType=4;
                              });
                            }, icon:payType==4?Icon(Icons.check_circle,color: MyColors.themeColor,): Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                          ],
                        ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    GestureDetector(
                      child:  Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("    "+"其他付款方式",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                          Row(
                            children: [
                              Text("其他付款方式",style: TextStyle(color:MyColors.authTipColor,fontSize: 14.sp),),
                              Icon(Icons.arrow_forward_ios,color: MyColors.authTipColor,size: 14,),
                              SizedBox(width: 10.w,),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
               ),

            ], 
          ),
          ),
          Container(
            color: Colors.white,
            width: screenSize.width,
            height: 85.h,
            padding: EdgeInsets.only(top: 10.h,right: 15.w,left: 15.w,bottom: 40.h),
            child:BrnSmallMainButton(
              title: '立即支付¥'+(insureStr).toString(),
              textColor: Colors.white,
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              bgColor: MyColors.themeColor,
              radius: 30,
              onTap: () {
                if(payType==-1){
                  BrnToast.show("请选择支付方式", context, duration: BrnDuration.short,);
                }else{
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return EnterPasswordDialog(dataMap: widget.dataMap, payType: widget.payType, freight:insureStr , freightType: widget.freightType,);
                    },
                  );
                }


              },
            ),
          )
        ],
      ) ,
    );
    
  }
}
class EnterPasswordDialog extends StatefulWidget {
  const EnterPasswordDialog({super.key, required this.dataMap, required this.payType, required this.freight, required this.freightType});
  final Map dataMap;
  final int payType;
  final String freight;
  final int freightType;
  @override
  State<EnterPasswordDialog> createState() => _EnterPasswordDialogState();
}

class _EnterPasswordDialogState extends State<EnterPasswordDialog> {
  TextEditingController _controller = TextEditingController();
  @override

  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Container(
        padding: EdgeInsets.all(16),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10))),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(),
                IconButton(
                  icon: Icon(Icons.close,color: Colors.black,),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
              ],
            ),

            Text(
              '请输入支付密码',
              style: TextStyle(
                color:MyColors.textColor,
                fontSize: 16.sp,
              ),
            ),
            SizedBox(height: 16),
          Container(
            // margin: EdgeInsets.only(left: 10.w,right:10.w),
            child: PinCodeTextField(
                obscureText:true,
                appContext: context,//context
                length: 6,//输入的长度
                controller: _controller,
                autoFocus: true,
                textStyle:TextStyle(color: Colors.black),
                cursorColor: Colors.black,
                pinTheme: PinTheme(

                  shape: PinCodeFieldShape.box, //输入框的形状
                  borderRadius: const BorderRadius.all(Radius.circular(0)),
                  activeColor:MyColors.themeColor,
                  selectedColor:MyColors.authTipColor,
                  inactiveColor:MyColors.backgreyColor,

                ),

                onChanged: (value)  async {

                  if(value.length==6) {


                    }

                  }
            ),
          ),

            SizedBox(height: 16),
            TextButton(
              onPressed: () {
                  Navigator.pop(context);
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) {
                      return PayAuthentication(phoneNum: '',
                      );
                    }));
              },
              child: Text('忘记密码？',
                style: TextStyle(
                  color: MyColors.themeColor,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

